package org.de.maeyer.sampler;

import static java.util.Collections.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.regex.Pattern;

import org.de.maeyer.unit.Unit;

/**
 * @author Peter De Maeyer
 */
public class ConcurrentSamplerManager implements SamplerManager {

	private final Map<String, ConcurrentSampler> samplers = new HashMap<String, ConcurrentSampler>();

	@Override
    public Counter getCounter(String name) {
		return getSampler(name);
    }

	@Override
    public DoubleSampler getDoubleSampler(String name) {
		return getSampler(name);
    }

	@Override
    public LongSampler getLongSampler(String name) {
		return getSampler(name);
    }

    @Override
    public ObjectSampler getObjectSampler(String name) {
		return getSampler(name);
    }

	@Override
    public Collection<Sampler> getSamplersContaining(String excerpt) {
		Collection<Sampler> matchingSamplers = new LinkedList<Sampler>();
		for (ConcurrentSampler sampler: samplers.values()) {
			if (sampler.getName().contains(excerpt)) {
				matchingSamplers.add(sampler);
			}
		}
		return unmodifiableCollection(matchingSamplers);
    }

	@Override
    public Collection<Sampler> getSamplersMatching(String regex) {
		Pattern pattern = Pattern.compile(regex);
		Collection<Sampler> matchingSamplers = new LinkedList<Sampler>();
		for (ConcurrentSampler sampler: samplers.values()) {
			if (pattern.matcher(sampler.getName()).matches()) {
				matchingSamplers.add(sampler);
			}
		}
		return unmodifiableCollection(matchingSamplers);
    }

	@Override
    public Collection<Sampler> getSamplersStartingWith(String prefix) {
		Collection<Sampler> matchingSamplers = new LinkedList<Sampler>();
		for (ConcurrentSampler sampler: samplers.values()) {
			if (sampler.getName().startsWith(prefix)) {
				matchingSamplers.add(sampler);
			}
		}
		return unmodifiableCollection(matchingSamplers);
    }

	@Override
    public Counter newCounter(String name) {
		return newSampler(null, name, null);
    }

	@Override
    public DoubleSampler newDoubleSampler(String name, Unit unit) {
		return newSampler(double.class, name, unit);
    }

	@Override
    public LongSampler newLongSampler(String name, Unit unit) {
		return newSampler(long.class, name, unit);
    }

    @Override
    public ObjectSampler newObjectSampler(String name, Unit unit) {
		return newSampler(Object.class, name, unit);
    }
	
	private ConcurrentSampler getSampler(String name) {
		return samplers.get(name);
	}
	
	private ConcurrentSampler newSampler(Class clazz, String name, Unit unit) {
		if (samplers.containsKey(name)) {
			throw new IllegalStateException("sampler name conflict: " + name);
		}
		return new ConcurrentSampler(clazz, name, unit);
	}
}